package com.jz.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jz.mapper.auto.TAdviseMapper;
import com.jz.module.dto.TAdviseDto;
import com.jz.module.dto.base.PageInfoDto;
import com.jz.module.entity.TAdvise;
import com.jz.module.entity.TAdviseExample;
import com.jz.service.AdviseService;
import com.jz.util.ResultUtil;
import com.jz.util.SysCode;
import com.jz.util.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AdviseServiceImpl implements AdviseService {

    @Autowired
    @SuppressWarnings("all")
    private TAdviseMapper tAdviseMapper;

    @Override
    public ResultUtil page(TAdviseDto dto) {
        PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
        TAdviseExample example = new TAdviseExample();
        example.setOrderByClause("create_time desc");
        List<TAdvise> tAdvises = tAdviseMapper.selectByExample(example);
        PageInfo<TAdvise> info = new PageInfo<>(tAdvises);
        PageInfoDto<TAdviseDto> result = new PageInfoDto<TAdviseDto>();
        BeanUtils.copyProperties(info, result);
        return ResultUtil.success(result);
    }

    @Override
    public ResultUtil query(TAdviseDto dto) {
        if (dto == null || StringUtils.isBlank(dto.getId())) {
            return ResultUtil.paramError();
        }
        TAdvise tAdvise = tAdviseMapper.selectByPrimaryKey(dto.getId());
        if (tAdvise == null) {
            return ResultUtil.error(SysCode.NO_DATA);
        }
        TAdviseDto result = new TAdviseDto();
        BeanUtils.copyProperties(tAdvise, result);
        return ResultUtil.success(result);
    }

    @Override
    public ResultUtil save(TAdviseDto dto) {
        if (dto == null || StringUtils.isAnyBlank(
                dto.getContent(),
                dto.getHostId(),
                dto.getHostName(),
                dto.getHostType()
        )) {
            return ResultUtil.paramError();
        }
        TAdvise insert = new TAdvise();
        BeanUtils.copyProperties(dto, insert);

        insert.setCreateTime(new Date());
        insert.setId(UUIDUtil.getUUID());
        int i = tAdviseMapper.insert(insert);
        if (i > 0) {
            return ResultUtil.success();
        }
        return ResultUtil.error(SysCode.INSERT_ERROR);
    }

    @Override
    public ResultUtil delete(TAdviseDto dto) {
        if (dto == null || StringUtils.isBlank(dto.getId())) {
            return ResultUtil.paramError();
        }
        int i = tAdviseMapper.deleteByPrimaryKey(dto.getId());
        if (i > 0) {
            return ResultUtil.success();
        }
        return ResultUtil.error(SysCode.DELETE_ERROR);
    }
}
